package com.csx.midware.redis;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.params.SetParams;

/**
 * redis 做分布式锁
 */
public class RedisLockExample {

    private Jedis jedis;

    public RedisLockExample() {
        jedis = new Jedis("localhost");
    }

    public boolean acquireLock(String lockKey, String requestId, int expireTime) {
        SetParams params = SetParams.setParams().nx().ex(expireTime);
        String result = jedis.set(lockKey, requestId, params);
        return "OK".equals(result);
    }

    public void releaseLock(String lockKey, String requestId) {
        String script = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";
        jedis.eval(script, 1, lockKey, requestId);
    }

    public static void main(String[] args) {
        RedisLockExample example = new RedisLockExample();
        String lockKey = "myLock";
        String requestId = "request123";
        int expireTime = 10;

        if (example.acquireLock(lockKey, requestId, expireTime)) {
            try {
                // 执行需要加锁的操作
                System.out.println("Lock acquired, performing operation...");
            } finally {
                example.releaseLock(lockKey, requestId);
                System.out.println("Lock released.");
            }
        } else {
            System.out.println("Failed to acquire lock.");
        }
    }
}